package fi.solita.dojo.mazeserver.ui

import swing._
import swing.event._
import javax.swing.table._
import java.awt.{ Color, Dimension, Graphics }
import fi.solita.dojo.mazeserver.game._

import SwingHelpers.inSwingThread

class PlayerListComponent extends ScrollPane(new PlayerListTable) {
	border = Swing.EmptyBorder(15, 10, 10, 10)
	preferredSize = new Dimension(500, 140)
}

class PlayerListTable extends Table {
	rowHeight = 25
	autoResizeMode = Table.AutoResizeMode.AllColumns
	showGrid = true
	gridColor = new java.awt.Color(150, 150, 150)

	selection.intervalMode = Table.IntervalMode.Single
 
	peer.setModel(PlayerListModel)
	listenTo(GameWorld)
	listenTo(ServerUI)

	reactions += {
	case PlayersAddedEvent(dto: PlayerList) =>
  		inSwingThread {
  		  PlayerListModel.dto = dto
          PlayerListModel.fireTableRowsInserted(PlayerListModel.getRowCount-1,
                                                PlayerListModel.getRowCount)
     	}
	case PlayersLeftEvent(dto: PlayerList) =>
	    inSwingThread {
  		  PlayerListModel.dto = dto
		  PlayerListModel.fireTableRowsDeleted(PlayerListModel.getRowCount, 
                                               PlayerListModel.getRowCount+1)
        }
	case PlayersUpdatedEvent(dto: PlayerList) =>
  		inSwingThread {
  		  PlayerListModel.dto = dto
		  repaint()
        }
	case RefreshEvent() => repaint()
	}
}

object PlayerListModel extends AbstractTableModel{
	var dto: PlayerList = new PlayerList(Nil)
	val columnNames = List("Color", "Name", "Points", "Row/Column", "Action", "Connected")
	override def getColumnName(column:  Int) = columnNames(column)
	def getColumnCount() = columnNames.size

	def getRowCount() = {
	  dto.players.length
	}
 
	def getValueAt(row: Int, col: Int): String = {
	  	if (row >= getRowCount) {
          return "XXXXXXXXXXXXXXXXXXXX" // FIXME
          }
	  	
		col match {
		case 0 => dto.players(row).color._2
		case 1 => dto.players(row).name
		case 2 => dto.players(row).points.toString
		case 3 => dto.players(row).coordinates.toString
		case 4 => dto.players(row).nextAction.toString
		case 5 => dto.playerConnected(dto.players(row)).toString
		case _ => ""
		}
	}
	override def isCellEditable(row: Int, column: Int) = false
}


object SwingHelpers {
  def inSwingThread(thunk: => Unit) {
    javax.swing.SwingUtilities.invokeLater(new Runnable {
      def run = thunk
    })
  }
}